<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />









  <meta name="baidu-site-verification" content="Q7ugSRSO7V" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Demo实例1&amp;lt;?php//PDO的预处理(添加操作),采用的是别名式参数SQL语句，绑定变量的方式赋值//导入配置文件require(&quot;config.php&quot;);//实例化PDO对象try&amp;#123;    $pdo = new PDO(DSN,USER,PASS);    //通过设置属性方法，将pdo对象的错误模式设置为异常模式    //$pdo-&amp;gt;setAttribute(P">
<meta property="og:type" content="article">
<meta property="og:title" content="pdo">
<meta property="og:url" content="http://yoursite.com/php/pdo/index.html">
<meta property="og:site_name" content="chimps">
<meta property="og:description" content="Demo实例1&amp;lt;?php//PDO的预处理(添加操作),采用的是别名式参数SQL语句，绑定变量的方式赋值//导入配置文件require(&quot;config.php&quot;);//实例化PDO对象try&amp;#123;    $pdo = new PDO(DSN,USER,PASS);    //通过设置属性方法，将pdo对象的错误模式设置为异常模式    //$pdo-&amp;gt;setAttribute(P">
<meta property="og:updated_time" content="2017-04-23T14:34:13.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="pdo">
<meta name="twitter:description" content="Demo实例1&amp;lt;?php//PDO的预处理(添加操作),采用的是别名式参数SQL语句，绑定变量的方式赋值//导入配置文件require(&quot;config.php&quot;);//实例化PDO对象try&amp;#123;    $pdo = new PDO(DSN,USER,PASS);    //通过设置属性方法，将pdo对象的错误模式设置为异常模式    //$pdo-&amp;gt;setAttribute(P">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":30},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/php/pdo/"/>





  <title> pdo | chimps </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?dcb994042608bdb310eff950ba755ff1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">chimps</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/php/pdo/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chimps">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="chimps">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                pdo
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-23T22:32:07+08:00">
                2017-04-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/php/" itemprop="url" rel="index">
                    <span itemprop="name">php</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/php/pdo/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Demo实例1"><a href="#Demo实例1" class="headerlink" title="Demo实例1"></a>Demo实例1</h1><figure class="highlight go"><table><tr><td class="code"><pre><div class="line">&lt;?php</div><div class="line"><span class="comment">//PDO的预处理(添加操作),采用的是别名式参数SQL语句，绑定变量的方式赋值</span></div><div class="line"></div><div class="line"><span class="comment">//导入配置文件</span></div><div class="line">require(<span class="string">"config.php"</span>);</div><div class="line"></div><div class="line"><span class="comment">//实例化PDO对象</span></div><div class="line">try&#123;</div><div class="line">    $pdo = <span class="built_in">new</span> PDO(DSN,USER,PASS);</div><div class="line">    <span class="comment">//通过设置属性方法，将pdo对象的错误模式设置为异常模式</span></div><div class="line">    <span class="comment">//$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);</span></div><div class="line">&#125;catch(PDOException $pe)&#123;</div><div class="line">   die(<span class="string">"实例化PDO失败！原因:"</span>.$pe-&gt;getMessage());</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//执行数据查询</span></div><div class="line">$sql = <span class="string">"insert into stu values(null,:name,:sex,:age,:classid)"</span>;</div><div class="line"><span class="comment">//sql语句的预处理，并返回PDOStatement预处理对象</span></div><div class="line">$stmt = $pdo-&gt;prepare($sql);</div><div class="line"></div><div class="line"><span class="comment">//为别名式sql语句中的占位符绑定变量</span></div><div class="line">$stmt-&gt;bindParam(<span class="string">"name"</span>,$name);</div><div class="line">$stmt-&gt;bindParam(<span class="string">"sex"</span>,$sex);</div><div class="line">$stmt-&gt;bindParam(<span class="string">"age"</span>,$age);</div><div class="line">$stmt-&gt;bindParam(<span class="string">"classid"</span>,$classid);</div><div class="line"></div><div class="line">$name=<span class="string">"wangba"</span>;</div><div class="line">$sex=<span class="number">1</span>;</div><div class="line">$age=<span class="number">22</span>;</div><div class="line">$classid=<span class="string">'lamp115'</span>;</div><div class="line"><span class="comment">//执行</span></div><div class="line">$stmt-&gt;execute();</div><div class="line"></div><div class="line"><span class="comment">//根据影响行数判断是否成功</span></div><div class="line"><span class="keyword">if</span>($stmt-&gt;rowCount()&gt;<span class="number">0</span>)&#123;</div><div class="line">    echo <span class="string">"添加成功！"</span>;</div><div class="line">    echo <span class="string">"自增id："</span>.$pdo-&gt;lastInsertId();</div><div class="line">&#125;<span class="keyword">else</span>&#123;</div><div class="line">    echo <span class="string">"添加失败！原因："</span>;</div><div class="line">    print_r($stmt-&gt;errorInfo());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="Demo实例2"><a href="#Demo实例2" class="headerlink" title="Demo实例2"></a>Demo实例2</h1><figure class="highlight go"><table><tr><td class="code"><pre><div class="line">&lt;?php</div><div class="line"></div><div class="line">require_once dirname(__FILE__).<span class="string">"/../config/config.php"</span>;</div><div class="line"></div><div class="line">class DB &#123;</div><div class="line">    static $pdo;</div><div class="line">    static $affectedRows;</div><div class="line">    static $errorInfo;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * CHDatabaseConnector constructor.</div><div class="line">     * Initialize PDO engine</div><div class="line">     */</div><div class="line">    static function init() &#123;</div><div class="line">        try&#123;</div><div class="line">            CMDatabaseConnector::$pdo=<span class="built_in">new</span> PDO(<span class="string">'mysql:dbname='</span> . $GLOBALS[<span class="string">"db_database"</span>] .<span class="string">';host='</span> . $GLOBALS[<span class="string">"db_host"</span>] . <span class="string">';charset=utf8mb4;port='</span> . $GLOBALS[<span class="string">"db_port"</span>], $GLOBALS[<span class="string">"db_username"</span>], $GLOBALS[<span class="string">"db_password"</span>]);</div><div class="line">        &#125;catch(PDOException $e)&#123;</div><div class="line">            echo $e-&gt;getMessage();</div><div class="line">            die();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * @param $statement</div><div class="line">     * @param null $paras</div><div class="line">     * @return array</div><div class="line">     */</div><div class="line">    static function read($statement, $paras=null, $order=null, $desc=<span class="literal">false</span>, $page=<span class="number">1</span>, $per_page=<span class="number">12</span>, &amp;$totalPage=null, &amp;$count=null)&#123;</div><div class="line">        <span class="keyword">if</span>(!CMDatabaseConnector::$pdo) CMDatabaseConnector::init();</div><div class="line">        <span class="keyword">if</span>($order==null)&#123;</div><div class="line">            $query=CMDatabaseConnector::$pdo-&gt;prepare($statement);</div><div class="line">            $query-&gt;execute($paras);</div><div class="line">            $res=$query-&gt;fetchAll(PDO::FETCH_ASSOC);</div><div class="line">            <span class="keyword">if</span> ($query-&gt;errorCode() != <span class="string">'00000'</span>)&#123;</div><div class="line">                self::$errorInfo=$query-&gt;errorInfo()[<span class="number">2</span>];</div><div class="line">                $GLOBALS[<span class="string">"error"</span>]=self::$errorInfo;</div><div class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">return</span> $res;</div><div class="line">        &#125;<span class="keyword">else</span>&#123;</div><div class="line">            $page=intval($page);</div><div class="line">            $per_page=intval($per_page);</div><div class="line">            <span class="keyword">if</span>($per_page&lt;=<span class="number">0</span>) $per_page=<span class="number">12</span>;</div><div class="line"></div><div class="line">            $start=$page*$per_page;</div><div class="line">            <span class="keyword">if</span>($desc)&#123;</div><div class="line">                $data=self::read($statement.<span class="string">" order by $order desc limit $start, $per_page"</span>, $paras);</div><div class="line">            &#125;<span class="keyword">else</span>&#123;</div><div class="line">                $data=self::read($statement.<span class="string">" order by $order limit $start, $per_page"</span>, $paras);</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            $count_statement=preg_replace(<span class="string">'# (select|SELECT)\s+(.+?)(\sFROM|from)(.+?)(GROUP BY|group by)(.+)# '</span>, <span class="string">'$1 count(distinct($6)) as c $3$4'</span>, $statement, <span class="number">-1</span>, $replace_count);</div><div class="line">            <span class="keyword">if</span>($replace_count==<span class="number">0</span>)&#123;</div><div class="line">                $count_statement=preg_replace(<span class="string">'# (select|SELECT)\s+(.+?)(\sFROM|from)# '</span>, <span class="string">'$1 count(*) as c $3'</span>, $statement, <span class="number">-1</span>, $replace_count);</div><div class="line">            &#125;</div><div class="line">            $count=self::get_first_match($count_statement, $paras, <span class="string">"c"</span>);</div><div class="line">            $totalPage=ceil($count/$per_page);</div><div class="line">            <span class="keyword">return</span> $data;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * @param $statement</div><div class="line">     * @param null $paras</div><div class="line">     * @return bool</div><div class="line">     */</div><div class="line">    static function write($statement, $paras=null, $debug=<span class="literal">false</span>)&#123;</div><div class="line">        <span class="keyword">if</span>($debug)&#123;</div><div class="line">            var_dump($statement, $paras);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(!CMDatabaseConnector::$pdo) CMDatabaseConnector::init();</div><div class="line">        $query=CMDatabaseConnector::$pdo-&gt;prepare($statement);</div><div class="line">        $query-&gt;execute($paras);</div><div class="line">        <span class="keyword">if</span> ($query-&gt;errorCode() != <span class="string">'00000'</span>)&#123;</div><div class="line">            self::$errorInfo=$query-&gt;errorInfo()[<span class="number">2</span>];</div><div class="line">            $GLOBALS[<span class="string">"error"</span>]=self::$errorInfo;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">        CMDatabaseConnector::$affectedRows=$query-&gt;rowCount();</div><div class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    static function getError()&#123;</div><div class="line">        <span class="keyword">return</span> self::$errorInfo;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    static function get_first_match($statement, $paras=null, $key=null)&#123;</div><div class="line">        $res=CMDatabaseConnector::read($statement, $paras);</div><div class="line">        <span class="keyword">if</span>(count($res)==<span class="number">0</span>) <span class="keyword">return</span> null;</div><div class="line">        $res=$res[<span class="number">0</span>];</div><div class="line">        <span class="keyword">if</span>($key) <span class="keyword">return</span> $res[$key];</div><div class="line">        <span class="keyword">else</span> <span class="keyword">return</span> $res;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    static function insert($table, $kv, $debug=<span class="literal">false</span>)&#123;</div><div class="line">        $excute=array();</div><div class="line">        $fakekeys=array();</div><div class="line">        $fakevalues=array();</div><div class="line">        $n=<span class="number">0</span>;</div><div class="line">        foreach($kv as $key=&gt;$value) &#123;</div><div class="line">            $currentValue = <span class="string">":value$n"</span>;</div><div class="line">            array_push($fakekeys, $key);</div><div class="line">            array_push($fakevalues, $currentValue);</div><div class="line">            <span class="keyword">if</span> (is_array($value)) $value=json_encode($value, JSON_UNESCAPED_UNICODE);</div><div class="line">            $excute[$currentValue] = $value;</div><div class="line">            $n++;</div><div class="line">        &#125;</div><div class="line">        $statement=<span class="string">"insert into $table ("</span>.join(<span class="string">","</span>, $fakekeys).<span class="string">") values ("</span>.join(<span class="string">","</span>, $fakevalues).<span class="string">")"</span>;</div><div class="line">        <span class="keyword">if</span>(!CMDatabaseConnector::write($statement, $excute, $debug))&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(CMDatabaseConnector::getAffectedRows()==<span class="number">0</span>)&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(CMDatabaseConnector::getInsertId() &gt; <span class="number">0</span>)&#123;</div><div class="line">            <span class="keyword">return</span> CMDatabaseConnector::getInsertId();</div><div class="line">        &#125;<span class="keyword">else</span>&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 插入多条数据</span></div><div class="line">    static function insertMultiple($table,$kv,$debug=<span class="literal">false</span>)&#123;</div><div class="line">        $excute=array();</div><div class="line">        $fakekeys=array();</div><div class="line">        $fakevalues=array();</div><div class="line">        <span class="keyword">if</span>(count($kv) &lt; <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        foreach ($kv[<span class="number">0</span>] as $k=&gt;$v)&#123;</div><div class="line">            array_push($fakekeys, $k);</div><div class="line">        &#125;</div><div class="line">        foreach($kv as $k=&gt;$v) &#123;</div><div class="line">            $currentValue = [];</div><div class="line">            foreach ($v as $key=&gt;$value)&#123;</div><div class="line">                $currentV = <span class="string">":value"</span>.$k.$key;</div><div class="line">                $currentValue[] = $currentV;</div><div class="line">                $excute[$currentV] = $value;</div><div class="line">            &#125;</div><div class="line">            $fakevalues[] = <span class="string">'('</span>.join(<span class="string">','</span>,$currentValue).<span class="string">')'</span>;</div><div class="line">        &#125;</div><div class="line">        $statement=<span class="string">"insert into $table ("</span>.join(<span class="string">","</span>, $fakekeys).<span class="string">") values "</span>.join(<span class="string">","</span>, $fakevalues);</div><div class="line">        <span class="keyword">if</span>(!CMDatabaseConnector::write($statement, $excute, $debug))&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(CMDatabaseConnector::getAffectedRows()==<span class="number">0</span>)&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    static function insertOrUpdate($table, $kv, $idkey=null)&#123;</div><div class="line">        $execute=array();</div><div class="line">        $fakekeys=array();</div><div class="line">        $fakevalues=array();</div><div class="line">        $updatevalues=array();</div><div class="line">        $n=<span class="number">0</span>;</div><div class="line">        foreach($kv as $key=&gt;$value) &#123;</div><div class="line">            $currentValue = <span class="string">":value$n"</span>;</div><div class="line">            array_push($fakekeys, $key);</div><div class="line">            array_push($fakevalues, $currentValue);</div><div class="line">            $execute[$currentValue] = $value;</div><div class="line">            array_push($updatevalues, $key.<span class="string">"="</span>.$currentValue);</div><div class="line">            $n++;</div><div class="line">        &#125;</div><div class="line">        $statement=<span class="string">"insert into $table ("</span>.join(<span class="string">","</span>, $fakekeys).<span class="string">") values ("</span>.join(<span class="string">","</span>, $fakevalues).<span class="string">") on duplicate key update "</span>.join(<span class="string">","</span>,$updatevalues);</div><div class="line">        <span class="keyword">if</span>(CMDatabaseConnector::write($statement, $execute)) &#123;</div><div class="line">            <span class="keyword">if</span> ($idkey) &#123;</div><div class="line">                $res=CMDatabaseConnector::get_first_match(<span class="string">"select * from $table where "</span>.join(<span class="string">" and "</span>,$updatevalues), $execute);</div><div class="line">                <span class="keyword">return</span> $res[$idkey];</div><div class="line">            &#125;<span class="keyword">else</span>&#123;</div><div class="line">                <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">            &#125;</div><div class="line">        &#125;<span class="keyword">else</span>&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    static function update($table, $kv, $condition_template, $condition=null, $debug=<span class="literal">false</span>)&#123;</div><div class="line">        <span class="keyword">if</span>(count($kv)==<span class="number">0</span>)&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125;</div><div class="line">        $updatevalues=array();</div><div class="line">        $execute=array();</div><div class="line">        $n=<span class="number">0</span>;</div><div class="line">        foreach($kv as $key=&gt;$value) &#123;</div><div class="line">            $currentValue = <span class="string">":value$n"</span>;</div><div class="line">            <span class="keyword">if</span> (is_array($value)) $value=json_encode($value, JSON_UNESCAPED_UNICODE);</div><div class="line">            $execute[$currentValue] = $value;</div><div class="line">            array_push($updatevalues, $key.<span class="string">"="</span>.$currentValue);</div><div class="line">            $n++;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>($condition)&#123;</div><div class="line">            foreach($condition as $key=&gt;$value)&#123;</div><div class="line">                $execute[$key]=$value;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        $statement=<span class="string">"update $table set "</span>.join(<span class="string">","</span>, $updatevalues).<span class="string">" where "</span>.$condition_template;</div><div class="line">        <span class="keyword">return</span> CMDatabaseConnector::write($statement, $execute, $debug);</div><div class="line">    &#125;</div><div class="line">    static function getAffectedRows()&#123;</div><div class="line">        <span class="keyword">return</span> CMDatabaseConnector::$affectedRows;</div><div class="line">    &#125;</div><div class="line">    static function getInsertId()&#123;</div><div class="line">        <span class="keyword">return</span> CMDatabaseConnector::$pdo-&gt;lastInsertId();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="连接时选择字符集"><a href="#连接时选择字符集" class="headerlink" title="连接时选择字符集"></a>连接时选择字符集</h1><figure class="highlight php"><table><tr><td class="code"><pre><div class="line">$pdo = <span class="keyword">new</span> PDO(<span class="string">'mysql:host=localhost;dbname=user'</span>,<span class="string">'root'</span>,<span class="string">''</span>);</div><div class="line">$pdo-&gt;exec(<span class="string">"SET NAMES utf8"</span>);</div><div class="line"></div><div class="line">原理：（</div><div class="line">假设我们把两个都设为utf8，然后在MySQL Command Line Client里面输入“show variebles like“character_set_%”;”，可看到如下字符：</div><div class="line">character_set_client   latin1</div><div class="line">character_set_connection    latin1</div><div class="line">character_set_database     utf8</div><div class="line">character_set_results    latin1</div><div class="line">character_set_server   utf8</div><div class="line">character_set_system     utf8</div><div class="line">要是我们通过采用UTF<span class="number">-8</span>的PHP程序从数据库里读取数据，很有可能是一串“?????”或者是其他乱码。</div><div class="line">解决办法是，在连接数据库之后，读取数据之前，先执行一项查询“SET NAMES UTF8”，即在PHP里为</div><div class="line">mysql_query(<span class="string">"SET NAMES UTF8"</span>);    </div><div class="line"><span class="comment">//该句话一定要放在数据库服务器连接语句【$connection=mysql_connect($db_host,$db_user,$db_psw)or die("连接服务器失败");】之后</span></div><div class="line">即可显示正常（只要数据库里信息的字符正常）。</div><div class="line">到MySQL命令行输入“SET NAMES UTF8;”，然后执行“show variebles like“character_set_%”;”，发现原来为latin1的那些变量“character_set_client”、“character_set_connection”、“character_set_results”的值全部变为utf8了，原来是这<span class="number">3</span>个变量在捣蛋。</div><div class="line">查阅手册，上面那句等于：</div><div class="line">SET character_set_client = utf8;       </div><div class="line">SET character_set_results = utf8;      </div><div class="line">SET character_set_connection = utf8;  </div><div class="line">）。</div></pre></td></tr></table></figure>
<h1 id="PHP操作MySQL数据库方式有三种："><a href="#PHP操作MySQL数据库方式有三种：" class="headerlink" title="PHP操作MySQL数据库方式有三种："></a>PHP操作MySQL数据库方式有三种：</h1><figure class="highlight php"><table><tr><td class="code"><pre><div class="line">*<span class="number">1.</span> mysql 最原始的、纯过程化的 如连接： mysql_connect(主机名，账号，密码);</div><div class="line">   mysql_query();</div><div class="line"><span class="number">2.</span> mysqli 改进版的、兼容过程化和面向对象化操作</div><div class="line">	如：连接： mysqli_connect(主机名，账号，密码，库名) <span class="comment">//过程化</span></div><div class="line">			   <span class="keyword">new</span> mysqli(主机名，账号，密码，库名)	<span class="comment">//面向对象		   </span></div><div class="line">*<span class="number">3.</span> PDO 通用的，兼容其他数据库 ， 纯面向对象方式</div><div class="line">	如： 连接： <span class="keyword">new</span> PDO(DSN,账号，密码); </div><div class="line">	选择PDO的原因：跨数据库，带预处理（防sql注入）、支持事务操作</div><div class="line">  <span class="comment">// $v ="' or ''='";</span></div><div class="line">  <span class="comment">// select * from stu where name='&#123;$v&#125;';</span></div><div class="line">  <span class="comment">//select * from stu where name='' or ''='';</span></div></pre></td></tr></table></figure>
<h1 id="PDO的环境配置：开启支持PDO"><a href="#PDO的环境配置：开启支持PDO" class="headerlink" title="PDO的环境配置：开启支持PDO"></a>PDO的环境配置：开启支持PDO</h1><pre><code>在php.ini配置文件中开启：
    extension=php_pdo.dll
    extension=php_pdo_mysql.dll    
在PDO操作中涉及到类：PDO、PDOStatement(预处理对象)、PDOException（异常类）
</code></pre><h1 id="PDO类的构造方法："><a href="#PDO类的构造方法：" class="headerlink" title="PDO类的构造方法："></a>PDO类的构造方法：</h1><pre><code>$pdo =  new PDO(&quot;mysql:host=localhost;dbname=lamp36db&quot;,&quot;root&quot;,&quot;root&quot;);
$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
</code></pre><h1 id="其他方法："><a href="#其他方法：" class="headerlink" title="其他方法："></a>其他方法：</h1><pre><code>1. query($sql); 用于执行查询SQL语句。返回PDOStatement对象
2. exec($sql);  用于执行增、删、改操作，返回影响行数；
3. getAttribute(); 获取一个&quot;数据库连接对象&quot;属性。
4. setAttribute(); 设置一个&quot;数据库连接对象&quot;属性。
5. beginTransaction 开启一个事物（做一个回滚点）
6. commit    提交事务
7. rollBack    事务回滚操作。 
8. errorCode    获取错误码   
9. errorInfo    获取错误信息   
10.lastInsertId  获取刚刚添加的主键值。
11.prepare    创建SQL的预处理，返回PDOStatement对象
12.quote    为sql字串添加单引号。
</code></pre><h1 id="预处理对象PDOStatement对象："><a href="#预处理对象PDOStatement对象：" class="headerlink" title="预处理对象PDOStatement对象："></a>预处理对象PDOStatement对象：</h1><pre><code>我们可以通过PDO的方法来获取PDOStatement：
 1.PDO的query（查询sql）方法获取，用于解析结果集
 2.PDO的prepare(SQL)方法获取，用于处理参数式sql并执行操作。
</code></pre><h1 id="PDOstatement对象的方法："><a href="#PDOstatement对象的方法：" class="headerlink" title="PDOstatement对象的方法："></a>PDOstatement对象的方法：</h1><figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="number">1</span>、fetch() 返回结果集的下一行，结果指针下移，到头返回<span class="keyword">false</span> 。</div><div class="line">  	参数： 	PDO::FETCH_BOTH (<span class="keyword">default</span>)、：索引加关联数组模式</div><div class="line">	       	PDO::FETCH_ASSOC、	   ：关联数组模式</div><div class="line"> 	       	PDO::FETCH_NUM、		   ：索引数组模式</div><div class="line">			PDO::FETCH_OBJ、		   ：对象模式</div><div class="line">			PDO::FETCH_LAZY		   ：所有模式（SQL语句和对象）</div><div class="line"><span class="number">2</span>、fetchAll() 通过一次调用返回所有结果，结果是以数组形式保存</div><div class="line">      	参数：PDO::FETCH_BOTH (<span class="keyword">default</span>)、</div><div class="line">		PDO::FETCH_ASSOC、</div><div class="line">		PDO::FETCH_NUM、</div><div class="line">		PDO::FETCH_OBJ、</div><div class="line">		PDO::FETCH_COLUMN表示取指定某一列，</div><div class="line">		如：$rslist = $stmt-&gt;fetchAll(PDO::FETCH_COLUMN,<span class="number">2</span>);取第三列</div><div class="line"><span class="number">3</span>、execute() 	负责执行一个准备好了的预处理语句 </div><div class="line"><span class="number">4.</span> fetchColumn()返回结果集中下一行某个列的值</div><div class="line"><span class="number">5.</span> setFetchMode()设置需要结果集合的类型</div><div class="line"><span class="number">6.</span> rowCount()  	返回使用增、删、改、查操作语句后受影响的行总数</div><div class="line"><span class="number">7.</span> setAttribute()为一个预处理语句设置属性</div><div class="line"><span class="number">8.</span> getAttribute()获取一个声明的属性</div><div class="line"><span class="number">9.</span> errorCode() 	获取错误码</div><div class="line"><span class="number">10.</span> errorInfo() 获取错误信息</div><div class="line"><span class="number">11.</span> bindParam() 将参数绑定到相应的查询占位符上</div><div class="line">    bool PDOStatement::bindParam ( mixed $parameter , mixed &amp;$variable [, int $data_type [, int $length [, mixed $driver_options ]]] ) </div><div class="line">    其中： $parameter：占位符名或索引偏移量 &amp;$variable:参数的值，需要按引用传递也就是必须放一个变量其中参数:$data_type:数据类型PDO::PARAM_BOOL/PDO::PARAM_NULL/PDO::PARAM_INT/PDO::PARAM_STR/</div><div class="line">PDO::PARAM_LOB/PDO::PARAM_STMT/PDO::PARAM_INPUT_OUTPUT</div><div class="line">    $length：指数据类型的长度 $driver_options：驱动选项。</div><div class="line"><span class="number">12.</span> bindColumn() 用来匹配列名和一个指定的变量名，这样每次获取各行记录时，会自动将相应的值赋给变量。</div><div class="line"><span class="number">13.</span> bindValue() 将一值绑定到对应的一个参数中</div><div class="line"><span class="number">14.</span> nextRowset() 检查下一行集</div><div class="line"><span class="number">15.</span> columnCount() 在结果集中返回列的数目</div><div class="line"><span class="number">16.</span> getColumnMeta() 在结果集中返回某一列的属性信息</div><div class="line"><span class="number">17.</span> closeCursor() 关闭游标，使该声明再次执行</div></pre></td></tr></table></figure>
<h1 id="在PDO中参数式的SQL语句有两种-预处理sql-："><a href="#在PDO中参数式的SQL语句有两种-预处理sql-：" class="headerlink" title="在PDO中参数式的SQL语句有两种(预处理sql)："></a>在PDO中参数式的SQL语句有两种(预处理sql)：</h1><figure class="highlight sql"><table><tr><td class="code"><pre><div class="line">1.insert into stu(id,name) value(?,?);	    //？号式（适合参数少的）		</div><div class="line">2.insert into stu(id,name) value(:id,:name);	// 别名式(适合参数多的)</div></pre></td></tr></table></figure>
<h1 id="在PDO中为参数式SQL语句赋值有三种："><a href="#在PDO中为参数式SQL语句赋值有三种：" class="headerlink" title="在PDO中为参数式SQL语句赋值有三种："></a>在PDO中为参数式SQL语句赋值有三种：</h1><pre><code>1.使用数组 
</code></pre><figure class="highlight php"><table><tr><td class="code"><pre><div class="line">$stmt-&gt;execute(<span class="keyword">array</span>(<span class="string">"lamp1404"</span>,<span class="string">"qq2"</span>));</div><div class="line">$stmt-&gt;execute(<span class="keyword">array</span>(<span class="string">"id"</span>=&gt;<span class="string">"lamp1404"</span>,<span class="string">"name"</span>=&gt;<span class="string">"qq2"</span>));	</div><div class="line"><span class="number">2.</span>使用方法单个赋值</div><div class="line">$stmt-&gt;bindValue(<span class="number">1</span>,<span class="string">"lamp1901"</span>);	</div><div class="line">$stmt-&gt;bindValue(<span class="number">2</span>,<span class="string">"qq2"</span>);</div><div class="line">$stmt-&gt;execute();</div><div class="line"></div><div class="line">$stmt-&gt;bindValue(<span class="string">":id"</span>,<span class="string">"lamp1901"</span>,PDO::PARAM_STR);	 <span class="comment">//带指定类型</span></div><div class="line">$stmt-&gt;bindValue(<span class="string">":name"</span>,<span class="string">"qq2"</span>,PDO::PARAM_STR);</div><div class="line">$stmt-&gt;execute();</div><div class="line"></div><div class="line"><span class="number">3.</span> 使用方法绑定变量</div><div class="line">$stmt-&gt;bindParam(<span class="string">":id"</span>,$id);		</div><div class="line">$stmt-&gt;bindParam(<span class="string">":name"</span>,$name);</div><div class="line">$id=<span class="string">"lamp1401"</span>;</div><div class="line">$name=<span class="string">"qq2"</span>;</div><div class="line">$stmt-&gt;execute();</div><div class="line">事务处理</div><div class="line">-----------------------------------------------</div><div class="line">事务：将多条sql操作（增删改）作为一个操作单元，要么都成功，要么都失败。-----</div></pre></td></tr></table></figure>
<h1 id="4-PDO对事务的支持"><a href="#4-PDO对事务的支持" class="headerlink" title="4.  PDO对事务的支持"></a>4.  PDO对事务的支持</h1><pre><code>第一：被操作的表必须是innoDB类型的表（支持事务）
    MySQL常用的表类型：MyISAM(非事务)增删改速度快、InnodB（事务型）安全性高
    //更改表的类型为innoDB类型
    mysql&gt; alter table stu engine=innodb;
        Query OK, 29 rows affected (0.34 sec)
        Records: 29  Duplicates: 0  Warnings: 0
    //查看表结构
    mysql&gt; show create table stu\G;   

第二：使用PDO就可以操作数据库了
    使用到了PDO中的方法：
        beginTransaction 开启一个事物（做一个回滚点）
        commit        提交事务
        rollBack    事务回滚操作。 
使用情况：当做多条sql语句处理时(增删改)，要求是都必须成功。 
</code></pre>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/php/网络/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/php/类与对象/" rel="prev" title="">
                 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256"
               alt="chimps" />
          <p class="site-author-name" itemprop="name">chimps</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Demo实例1"><span class="nav-number">1.</span> <span class="nav-text">Demo实例1</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Demo实例2"><span class="nav-number">2.</span> <span class="nav-text">Demo实例2</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#连接时选择字符集"><span class="nav-number">3.</span> <span class="nav-text">连接时选择字符集</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PHP操作MySQL数据库方式有三种："><span class="nav-number">4.</span> <span class="nav-text">PHP操作MySQL数据库方式有三种：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PDO的环境配置：开启支持PDO"><span class="nav-number">5.</span> <span class="nav-text">PDO的环境配置：开启支持PDO</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PDO类的构造方法："><span class="nav-number">6.</span> <span class="nav-text">PDO类的构造方法：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#其他方法："><span class="nav-number">7.</span> <span class="nav-text">其他方法：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#预处理对象PDOStatement对象："><span class="nav-number">8.</span> <span class="nav-text">预处理对象PDOStatement对象：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PDOstatement对象的方法："><span class="nav-number">9.</span> <span class="nav-text">PDOstatement对象的方法：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在PDO中参数式的SQL语句有两种-预处理sql-："><span class="nav-number">10.</span> <span class="nav-text">在PDO中参数式的SQL语句有两种(预处理sql)：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#在PDO中为参数式SQL语句赋值有三种："><span class="nav-number">11.</span> <span class="nav-text">在PDO中为参数式SQL语句赋值有三种：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-PDO对事务的支持"><span class="nav-number">12.</span> <span class="nav-text">4.  PDO对事务的支持</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chimps</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "48bb30d8783d4b38ba0c95e0283238ca",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  










  





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
